package org.vectrics.mail.struts;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;

import org.hibernate.Query;
import org.hibernate.Session;
import org.vectrics.SystemException;
import org.vectrics.common.util.StringUtils;
import org.vectrics.cv.Department;
import org.vectrics.dataweb.WebServiceAction;
import org.vectrics.hibernate.ThreadProperties;
import org.vectrics.struts.Request;
import org.w3c.dom.Element;

public class FindDepartmentWebService extends WebServiceAction {
	public static String COMMAND = "get.cv.departament";
	
	public FindDepartmentWebService() {
		super();
	}

	@Override
	public void getData(Request request, String command,
			Element requestElement, Element responseElement) {
		if (command.equals(COMMAND)) {
			Element dataElement = this.getDataElement(responseElement);
			String areaId = request.getParameter("areaId");
			log.info("Finding department for id = " + areaId);
			if (StringUtils.isNullOrBlank(areaId) == false) {
				Long idArea = new Long(areaId);
				Collection<Department> departments = new ArrayList<Department>();
				if (idArea != null){
					Session session = ThreadProperties.getSession();
					Query query = session.createQuery("from Department d  where d.area.id = :idArea");
					query.setParameter("idArea", idArea);
					departments.addAll(query.list());
					for ( Department department : departments) {
						Element departmentElement = responseElement.getOwnerDocument().createElement(
						"department");
				        this.departmentToElement(department, departmentElement);
				        dataElement.appendChild(departmentElement);
					}
				}
				
			    //seteo la request las Departamentos 
				request.setAttribute("allDepartment", departments);
			} else {
				throw new SystemException("Area ID not found: " + areaId);
			}
		}
	}

	private void departmentToElement(Department department,
			Element departmentElement) {
		departmentElement.setAttribute("id", department.getId().toString());
		departmentElement.setAttribute("description", department.getDescription());		
	}

	
}
